package EX3;
/*
    ObjectInputStream类 和 ObjectOutputStream类
    传送的对象数据，对象流是字节流
        前提条件：传输的对象必须被序列化（实现Serializable接口）
                写对象时，把对象序列化后写入目标文件
                读对象时，从目标文件反序列化对象再读取
 */

import java.io.*;

class User implements Serializable{
    String name,sex;
    int age;

    public User(String name, String sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name +
                ", sex='" + sex +
                ", age=" + age +
                '}';
    }
}
public class demo3 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        User user1=new User("张三","男",13);
        User user2=new User("李四","男",13);
        User user3=new User("王食","女",13);
        File f=new File("C:/filea/a.txt");
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(f));
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream(f));

        oos.writeObject(user1);
        oos.writeObject(user2);
        oos.writeObject(user3);

        oos.flush();
        oos.close();
        System.out.println("对象写入成功！");

        User obj;
        try {
            while ((obj = (User) ois.readObject()) != null) {
                System.out.println(obj);
            }
        }catch (EOFException e){
            ois.close();
        }
        /*
        从输入流中读取到的对象不为null，就继续执行循环体内的代码
        当读至文件末尾并且没有更多对象可读取,readObject()方法将抛出一个 EOFException（意味着文件结束）而不是返回 null
         */

    }
}
